package loengud.w05;

import java.util.Arrays;

/**
 * Code from week 5, 03.10.2013 lecture.
 * Example program to deal with arguments.
 * 
 * As can be seen from help method, 
 * our program expects at least 1 argument.
 * The program adds up all the arguments
 * and returns the sum. Optionally, the 
 * operation can be switched to multiplication
 * with a proper option argument.
 * @author Ago
 *
 */
public class Arguments {

	/**
	 * The main.
	 * @param args Arguments, which we will use this time.
	 */
	public static void main(String[] args) {
		
		// to try different arguments quickly in eclipse
		// without changing run configuration
		//String[] args2 = {"0", "5", "4"}; // new String[] {}
		//args = args2;
		
		if (args.length == 0) {
			// no arguments, let's show help
			help(1);
		}
		if (args[0].equals("-h")) {
			help(0);
		}
		System.out.println(args);
		System.out.println(Arrays.toString(args));
		boolean isMultiplication = false;
		
			int result = 0;
			if (args[0].equals("-m")) {
				// let's use multiplication instead of sum
				isMultiplication = true;
				// because we multiply all the numbers
				// we cannot start with 0
				// because 0 * whatever = 0
				result = 1;
			}
			for (int i = 0; i < args.length; i++) {
				if (isMultiplication && i == 0) continue;
				try {
					int a = Integer.parseInt(args[i]);
					if (isMultiplication) {
						// result = result * a;
						result *= a;
					} else {
						// result = result + a
						result += a;
					}
				} catch (NumberFormatException e) {
					System.out.println("not a number: " + args[i]);
					// to test %ERRORLEVEL%
					help(13);
				}
			}
			System.out.println("result is " + result);
	}

	/**
	 * Prints out usage text with help about arguments.
	 * After the usage text is printed, program exits.
	 * @param errorCode Error code to be used for System.exit()
	 */
	public static void help(int errorCode) {
		System.out.println("Usage program [option] number1 [number2 [number 3 [..]]]");
		System.out.println("options:");
		System.out.println("  -m  multiply numbers");
		System.out.println("  -h  print help");
		System.exit(errorCode);
	}
}
